<template>
  <div class="app-container">
    <div style="font-size: 25px;">添加采购订单</div>
    <!--横线组件纯纯为了页面好看-->
    <el-divider></el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="采购单号" prop="poNo">
            <el-input v-model="pono" placeholder="请输入采购单号" style="width: 230px;" oninput="value=value.replace(/[^\d\w]/g,'')" maxlength="25"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" @change="suppliername" style="width: 230px;">
              <el-option
                v-for="dict in supplierlist"
                :key="dict.id"
                :label="dict.supplierName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款方式" prop="paymentType">
            <el-select v-model="form.paymentType" placeholder="请选择付款方式" style="width: 230px;">
              <el-option
                v-for="dict in dict.type.erp_payment_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商联系人" prop="supplieruser">
            <el-input v-model="supplieruser" placeholder="请输入供应商联系人" style="width: 230px;" maxlength="25"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商手机号" prop="supplierphone">
            <el-input v-model="supplierphone"
                      placeholder="请输入供应商手机号"
                      style="width: 230px;"
                      maxlength="15"
                      @input="v => supplierphone = v.replace(/[^\d]/g,'')"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="退货状态" prop="returnGoods" v-show="false">
        <el-input v-model="form.returnGoods = 1" placeholder="请输入退货状态" style="width: 230px;"/>
      </el-form-item>
      <el-form-item label="审核类型" prop="processType" v-show="false">
        <el-input v-model="form.processType = 1" placeholder="请输入审核类型" style="width: 230px;"/>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注"  style="width: 85%" maxlength="250"/>
      </el-form-item>
    </el-form>
    <!--横线组件纯纯为了页面好看-->
    <el-divider></el-divider>
    <el-row style="margin-bottom: 20px;">
      <el-col :span="1.5">
        <div style="font-size: 20px; margin-top: 5px">采购商品</div>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">点击添加商品</el-button>
      </el-col>
    </el-row>
    <el-table :data="addGoodsList" show-summary :summary-method="getSummaries">
      <el-table-column label="商品ID" align="center" prop="id"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="分类" align="center" prop="categoryName"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="采购单价" align="center" prop="price">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.price" placeholder="请输入价格"
                    size="mini"
                    style="width:100px"
                    maxlength="10"
                    @keyup.native="scope.row.price = scope.row.price = scope.row.price.replace(/[^\d.]/g,'');
                                   scope.row.price = scope.row.price.replace(/\.{2,}/g,'.');
                                   scope.row.price = scope.row.price.replace(/^\./g,'');
                                   scope.row.price = scope.row.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                   scope.row.price = scope.row.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
                    @input="handleEdit(scope.$index, scope.row)"></el-input>
        </div>
      </el-table-column>
      <el-table-column label="采购数量" align="center" prop="quantity">
        <div class="item" slot-scope="scope">
          <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1" :max="90000000000" size="mini" style="width:100px"  @input="handleEdit(scope.$index, scope.row)"/>
        </div>
      </el-table-column>
      <el-table-column label="采购总价" align="center" prop="total">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.total" placeholder="销售总价" size="mini" style="width:100px" readonly="readonly"></el-input>
        </div>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="deleteGoodsList(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >删除商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitForm">保存采购订单</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>

  <!--选择商品信息弹出框-->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal = "false" width="1500px" append-to-body>
      <el-form :model="queryParamsGoods" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParamsGoods.name"
            placeholder="请输入商品名称"
            clearable
            maxlength="35"
            @keyup.enter.native="handleQueryGoods"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
            v-model="queryParamsGoods.brandId"
            placeholder="请选择品牌"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQueryGoods"
          >
            <el-option
              v-for="dict in brandList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上下架" prop="shelves">
          <el-select
            v-model="queryParamsGoods.shelves"
            placeholder="请输入上下架"
            clearable
            @keyup.enter.native="handleQueryGoods"
          >
            <el-option label="上架" value=1 />
            <el-option label="下架" value=0 />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <treeselect v-model="queryParamsGoods.categoryId" :options="categoryOptions" :normalizer="normalizer"
                      placeholder="选择分类"
                      style="width: 230px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryGoods">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="商品ID" align="center" prop="id"/>
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="分类" align="center" prop="categoryName"/>
        <el-table-column label="品牌" align="center" prop="brandName"/>
        <el-table-column label="单位" align="center" prop="companyName"/>
        <el-table-column label="库存" align="center" prop="inventory"/>
        <el-table-column label="成本单价" align="center" prop="cost"/>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="addGood(scope.row)"
              v-hasPermi="['system:goods:edit']"
            >添加商品
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParamsGoods.pageNum"
        :limit.sync="queryParamsGoods.pageSize"
        @pagination="getGoodsList"
      />
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button @click="cancelGoods">关闭页面</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase } from "@/api/erp/purchase";
import {getSupplier, listSupplier} from "@/api/erp/supplier";
import {getGoods, listGoods} from "@/api/erp/goods";
import {listBrand} from "@/api/erp/brand";
import {listCategory} from "@/api/erp/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "add",
  components: {Treeselect},
  dicts: ['erp_warehousing_type', 'erp_return_goods', 'erp_process_type', 'erp_payment_type'],
  data() {
    return {
      //随机生成的订单编号
      pono:"",
      supplieruser:"",
      supplierphone:"",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //品牌列表
      brandList: [],
      //分类列表
      categoryOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      purchaseList: [],
      //供应商数据
      supplierlist: [],
      // 商品信息表格数据
      goodsList: [],
      // 添加的商品信息表格数据
      addGoodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        poNo: null,
        goodsIds: null,
        supplierId: null,
        supplieruser: null,
        supplierphone: null,
        paymentType: null,
        warehousingType: null,
        returnGoods: null,
        processType: null,
        createUser: null,
        gettime:"",
        //采购单价
        monovalents: "",
        //采购数量
        quantitys: "",
        //采购总价
        totalPrices: "",

      },
      //供应商查询参数
      queryParamsSupplier: {
        pageNum: 1,
        pageSize: 10,
        supplierName: null,
        supplierContacts: null,
        supplierPhone: null,
        supplierCategory: null,
        supplierAddress: null,
        supplierBank: null,
        supplierBankAccount: null,
        supplierDutyParagraph: null,
        detailedAddress: null,
        remarks: null,
        creatTime: null,
        creatUser: null
      },
      // 查询参数
      queryParamsGoods: {
        pageNum: 1,
        pageSize: 10,
        goodsIds: null,
        name: null,
        brandId: null,
        categoryId: null,
        type: null,
        labels: null,
        barCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    //生成随机的订单编号方法
    this.getCurrentTime();
    //查询商品表方法
    this.getGoodsList();
    //查询供应商列表方法
    this.getSupplierlist();
  },
  methods: {
    //查询供应商方法
    getSupplierlist(){
      listSupplier(this.queryParamsSupplier).then(response => {
        this.supplierlist = response.rows;
      });
    },
    /*选择供应商时的监听*/
    suppliername(val){
      const id = val
      getSupplier(id).then(response => {
        this.supplieruser = response.data.supplierContacts
        this.supplierphone = response.data.supplierPhone

      });
    },
    /** 查询商品列表 */
    getGoodsList() {
      this.loading = true;
      listGoods(this.queryParamsGoods).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //单个添加商品方法
    addGood(row) {
      for (var i = 0; i < this.addGoodsList.length; i++) {
        let newVar = this.addGoodsList[i];
        if (row.id === newVar.id) {
          this.$modal.alertError("以添加过此商品!");
          return;
        }
      }
      this.goodPrice =  row.price ;
      this.addGoodsList.push(row);
    },



    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },

    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "total"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },

    //商品总价计算
    handleEdit(index, row) {
      if(row.quantity && row.price){
        row.total = parseFloat(Number(row.quantity)*Number(row.price)).toFixed(2)
      }
    },
    // 获取当前日期的方法
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear().toString();
      let mm = (new Date().getMonth()+1).toString();
      let dd = new Date().getDate().toString();
      let hh = new Date().getHours().toString();
      let mf = (new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes()).toString();
      let ss = (new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds()).toString();
      _this.pono = "PONo"+yy+mm+dd+hh+mf+ss+ Math.floor(Math.random() * 10000)
    },
    //node分类节点
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.$router.push({path: '/purchase/purchase'});
    },
    //采购商品列表取消按钮
    cancelGoods() {
      this.open = false;
      this.resetGoods();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        poNo: null,
        supplierId: null,
        paymentType: null,
        warehousingType: null,
        returnGoods: null,
        supplieruser: null,
        supplierphone: null,
        processType: null,
        createTime: null,
        updateTime: null,
        createUser: null
      };
      this.resetForm("form");
    },
    // 添加商品表单重置
    resetGoods() {
      this.formGoods = {
        id: null,
        name: null,
        thumbnail: null,
        banners: null,
        description: null,
        sortDescription: null,
        price: null,
        brandId: null,
        categoryId: null,
        cost: null,
        type: null,
        details: null,
        labels: null,
        inventory: null,
        sales: null,
        weight: null,
        supplierId: null,
        shelves: null,
        shopId: null,
        sort: null,
        createTy: null,
        updateTime: null,
        createTime: null,
        barCode: null,
        speclist: null,
        speclabellist: null
      };
      this.resetForm("formGoods");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /*商品搜索按钮*/
    handleQueryGoods() {
      this.queryParamsGoods.pageNum = 1;
      this.getGoodsList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQueryGoods();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增采购商品按钮操作 */
    handleAdd() {
      this.getBrandList();
      this.getCategoryList();
      this.open = true;
      this.title = "选择商品";
    },
    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },
    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchase(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 新增提交按钮 */
    submitForm() {
      let that = this;
      this.$modal.confirm('是否确认保存采购订单？').then(function() {
        // 判断是否填写采购单号
        if (that.pono === "") {
          that.$modal.msgError("请填写采购单号");
          return;
        }
        // 判断是否选择供应商
        if (that.form.supplierId === undefined) {
          that.$modal.msgError("请选择供应商");
          return;
        }
        //判断是否选择付款方式
        if (that.form.paymentType === undefined) {
          that.$modal.msgError("请选择付款方式");
          return;
        }
        //判断是否填写供应商联系人
        if (that.supplieruser === "") {
          that.$modal.msgError("请填写供应商联系人");
          return;
        }
        //判断是否填写供供应商手机号
        if (that.supplierphone === "") {
          that.$modal.msgError("请填写供应商手机号");
          return;
        }
        //判断是否添加商品
        if (that.addGoodsList.length === 0) {
          that.$modal.msgError("请添加商品");
          return;
        }
        if (that.addGoodsList.length !== 0) {
          for (let i = 0; i < that.addGoodsList.length; i++) {
            if (that.addGoodsList[i].price === null || that.addGoodsList[i].price === "") {
              that.$modal.msgError("请填写采购单价");
              return;
            }
            if (that.addGoodsList[i].quantity === null || that.addGoodsList[i].quantity === undefined) {
              that.$modal.msgError("请填写采购数量");
              return;
            }
            if (that.addGoodsList[i].quantity <= 0) {
              that.$modal.msgError("请填写正确的采购数量");
              return;
            }
          }
        }
        //商品id数组
        let goodsId = [];
        //采购单价数组
        let monovalent = [];
        //采购数量数组
        let quantity = [];
        //采购总价数组
        let totalPrice = [];
        for (let i = 0; i < that.addGoodsList.length; i++) {
          //获得商品id
          goodsId.push(that.addGoodsList[i].id)
          //获得采购单价
          monovalent.push(that.addGoodsList[i].price)
          //获得采购数量
          quantity.push(that.addGoodsList[i].quantity)
          //获得采购总价
          totalPrice.push(that.addGoodsList[i].total)
        }
        //将获得的商品id以数组的形式传到后台
        that.form.goodsIds = goodsId;
        //将获得的采购单价以数组的形式传到后台
        that.form.monovalents = monovalent;
        //将获得的采购数量以数组的形式传到后台
        that.form.quantitys = quantity;
        //将获得的采购总价以数组的形式传到后台
        that.form.totalPrices = totalPrice;
        //将采购订单传回后台
        that.form.poNo = that.pono
        //将供应商联系人传回后台
        that.form.supplieruser = that.supplieruser
        //将供应商手机号传回后台
        that.form.supplierphone = that.supplierphone
        //调取新增接口
        addPurchase(that.form).then(response => {
          that.$modal.msgSuccess("新增成功");
          that.open = false;
          that.getList();
          that.cancel();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + ids + '"的数据项？').then(function() {
        return delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>

</style>
